package com.example.dzbsh.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class CreateJSON {

	public static void createJson(String JsonString,String filepath,String filename,HttpServletRequest request, HttpServletResponse response) {


		String fullurl=filepath+filename;

		try {
			// 保证创建一个新文件
			File file = new File(fullurl);
			if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
				file.getParentFile().mkdirs();
			}
			if (file.exists()) { // 如果已存在,删除旧文件
				file.delete();
			}
			file.createNewFile();

			// 将格式化后的字符串写入文件
			Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			write.write(JsonString);
			write.flush();
			write.close();

			// 输出
			reutrnfile(filepath,filename,request,response);
		} catch (Exception e){
			e.printStackTrace();
		}

	}

	//读取json文件
	public static String readJsonFile(String fileLujing) {
		//fileName="./json/test.json";
		String jsonStr = "";
		try {
			File jsonFile = new File(fileLujing);
			FileReader fileReader = new FileReader(jsonFile);
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			fileReader.close();
			reader.close();
			jsonStr = sb.toString();
			return jsonStr;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void reutrnfile(String filepath,String filename,
								  HttpServletRequest request,HttpServletResponse response) throws IOException {
		ServletOutputStream out = null;
		FileInputStream ips = null;
		try {

			// 获取文件存放的路径
			File file = new File(filepath + filename);
			String newFileName = filename;
			if (!file.exists()) {
				// 如果文件不存在就跳出
				return;
			}
			ips = new FileInputStream(file);
			response.setContentType("multipart/form-data");
			// 为文件重新设置名字，采用数据库内存储的文件名称
			response.addHeader("Content-Disposition", "attachment; filename=\""
					+ newFileName
					+ "\"");
			out = response.getOutputStream();
			// 读取文件流
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = ips.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.flush();
			ips.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


}
